Imports Janus.Windows.GridEX
Imports System.IO

Public Class frmPOSTouch
    Dim dvFood As DataView
    Dim pricedec, QtyDec, PercentDec, SumDec As Integer
    Dim CashAct As String = ""
    Public TableCode As String
    Public DocEntry As String = ""
    Private Sub frmTableDetail_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Cursor = Cursors.WaitCursor

            Me.lblCaption.Text = "TOUCH SALES"
            'Dim r As Rectangle
            'r = Me.GridMenu.GetCardBounds(GridMenu.Row)
            'r.Height = 300
            'Me.GridMenu.ExpandableCards = False

            dvFood = Functions.SAP_Local_RunQuery("select convert(nvarchar(500),isnull((select bitmappath from oadp),'')) + convert(nvarchar(500),isnull(PicturName,'')) PicturePath,isnull(PicturName,'') PicFileName, T1.ItemCode Item_Code, T1.ItemName Item_Name,T0.MENU_Code from _MenuDetail T0 with(nolock) join OITM T1 with(nolock)  on T0.ITEM_Code=T1.ItemCode").DefaultView
            LoadBackGroundPicture()

            '----------------------------LOAD MENU-------------------------------------
            Dim dtMenu As DataTable = Functions.SAP_Local_RunQuery("select menu_Code, Menu_Name from _Menu")
            GridMenu.DataSource = dtMenu
            If dtMenu.Rows.Count > 0 Then
                GridMenu.Row = 0
                FoodGridEX_Click(sender, e)
            End If
            

            '--------------------DECIMAL SETTING--------------
            Dim dtDecimal As DataTable = Functions.SAP_Local_RunQuery("select pricedec,QtyDec,PercentDec,SumDec from oadm")
            If dtDecimal.Rows.Count > 0 Then
                pricedec = dtDecimal.Rows(0).Item("pricedec")
                QtyDec = dtDecimal.Rows(0).Item("QtyDec")
                PercentDec = dtDecimal.Rows(0).Item("PercentDec")
                SumDec = dtDecimal.Rows(0).Item("SumDec")

                GridBill.RootTable.Columns("Price").FormatString = "{0:n" + CStr(pricedec) + "}"
                GridBill.RootTable.Columns("Total").FormatString = "{0:n" + CStr(SumDec) + "}"
                GridBill.RootTable.Columns("Quantity").FormatString = "{0:n" + CStr(QtyDec) + "}"
            Else
                MessageBox.Show("There's no decimal setup")
                Me.Close()
            End If

            '------------------CASH ACCOUNT-----------------
            Dim dtCash As DataTable = Functions.SAP_Local_RunQuery("select top(1) linkact_3 from oacp")
            If dtCash.Rows.Count > 0 Then
                CashAct = dtCash.Rows(0).Item("linkact_3").ToString
            Else
                MessageBox.Show("No Cash Account Setup")
                Me.Close()
            End If

            If DocEntry <> "" Then
                LoadDocument(DocEntry, "17")
            Else
                '------------------------LOAD ONETIME CUSTOMER ------------------
                Dim dtOneTimeCustomer As DataTable = Functions.SAP_Local_RunQuery("Select CardCode,CardName,Address from OCRD where CardCode=(select top(1) DfltCard from oacp)")

                If dtOneTimeCustomer.Rows.Count = 0 Then
                    Dim frm As New frmGeneralList
                    frm.QueryStr = "Select CardCode,CardName from OCRD where CardType='C'"
                    If frm.ShowDialog = Windows.Forms.DialogResult.OK Then
                        If frm.GridStep1.GetValue("CardCode").ToString <> "" Then
                            dtOneTimeCustomer = Functions.SAP_Local_RunQuery("Select CardCode,CardName,Address from OCRD where CardCode='" + frm.GridStep1.GetValue("CardCode").ToString + "'")
                        Else
                            MessageBox.Show("Please choose one time customer")
                            Me.Close()
                        End If
                    Else
                        MessageBox.Show("Please choose one time customer")
                        Me.Close()
                    End If
                End If
                GridCustomer.DataSource = dtOneTimeCustomer
            End If
            Me.Cursor = Cursors.Default

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
            Me.Cursor = Cursors.Default
        End Try
    End Sub
#Region "Grid Events"
    Private Sub GridMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GridMenu.Click
        Dim strId As String = GridMenu.GetValue("Id")
        If strId Is DBNull.Value Then
            Return
        End If

        Me.FoodGridEX.Enabled = True
        filterFood("Menu_Code=" + strId, False)
    End Sub
    Private Sub FoodGridEX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FoodGridEx.Click
        If FoodGridEX.RowCount = 0 Then Return 'Frank added this, neu ko item nao thi thoat

        If FoodGridEX.SelectedItems.Count() <= 0 Then
            Return
        End If

        AddItem2Bill()
    End Sub
    Private Sub GridBill_ColumnButtonClick(ByVal sender As System.Object, ByVal e As Janus.Windows.GridEX.ColumnActionEventArgs) Handles GridBill.ColumnButtonClick
        Select Case e.Column.Key
            Case "Quantity"
                Dim frm As New frmNumPad

                If frm.ShowDialog = Windows.Forms.DialogResult.OK Then
                    'GridBill.SetValue("Quantity", frm.txtResult.text)

                End If
            Case "Dscription"
                Dim frm As New frmMemo
                If frm.ShowDialog = Windows.Forms.DialogResult.OK Then
                    GridBill.SetValue("Dscription", GridBill.GetValue("ItemName") + frm.txtMemo.Text)
                    GridBill.UpdateData()
                End If
            Case "Increase"
                GridBill.SetValue("Quantity", GridBill.GetValue("Quantity") + 1)
                GridBill.UpdateData()
            Case "Decrease"
                GridBill.SetValue("Quantity", GridBill.GetValue("Quantity") - 1)
                GridBill.UpdateData()
            Case "Delete"
                GridBill.CurrentRow.Delete()
        End Select
    End Sub
#End Region
#Region "Button Events"
    Private Sub btnQuickComplele_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuickComplele.Click
        Try
            Dim frm As New frmAction
            frm.ShowDialog()
            Select Case frm.ActionType
                Case "17" 'SO
                    POST2SAP("17", "")
                Case "13" 'AR
                    POST2SAP("13", "")
                Case "15" 'DO
                    POST2SAP("15", "")
                Case "1324" 'Invoice and Cash
                    POST2SAP("15", "CASH")
                Case "1324xx" 'Invoice and Advance
                    POST2SAP("15", frm.CreditCard)
                Case Else
            End Select
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub
#End Region
#Region "Functions"
    Private Sub UpdateBill()
        GridBill.UpdateData()
        Dim SubTotal As Double = 0
        Dim TaxTotal As Double = 0
        For Each tempRow As GridEXRow In Me.GridBill.GetRows()
            SubTotal = SubTotal + CDbl(tempRow.Cells("Total").Value)
            TaxTotal = TaxTotal + CDbl(tempRow.Cells("Total").Value) * CDbl(tempRow.Cells("VatPrcnt").Value) / 100
        Next

        Dim Discount As Double = 0

        lblSubTotal.Text = String.Format("{0:n" + CStr(SumDec) + "}", SubTotal)
        lblTax.Text = String.Format("{0:n" + CStr(SumDec) + "}", TaxTotal)

        lblBalanceDue.Text = String.Format("{0:n" + CStr(SumDec) + "}", SubTotal - Discount + TaxTotal)
    End Sub
    Private Sub filterFood(ByVal connFilter As String, ByVal isSetMenu As Boolean)
        Try
            dvFood.RowFilter = Nothing
            dvFood.RowFilter = connFilter
            FoodGridEX.DataSource = dvFood
            If FoodGridEx.RowCount > 0 Then FoodGridEx.Row = 0

            Dim rowTemp As GridEXRow

            For i As Integer = 0 To FoodGridEx.RowCount - 1
                FoodGridEx.Row = i
                rowTemp = FoodGridEx.CurrentRow
                If File.Exists(rowTemp.Cells("PicturePath").Text) Then
                    imgListFood.Images.Add("Food" & i, Image.FromFile(rowTemp.Cells("PicturePath").Text))
                    rowTemp.Cells("Item_Name").Image = imgListFood.Images(1)
                End If
            Next
        Catch ex As Exception
        End Try
    End Sub
    Private Function findRowGridBillById(ByVal ItemCode As String) As GridEXRow
        For Each tempRow As GridEXRow In Me.GridBill.GetRows()
            If tempRow.Cells("ItemCode").Text = ItemCode Then
                Return tempRow
            End If
        Next
        Return Nothing
    End Function
    Private Function GetSAPItemPrice(ByVal cardCode As String, ByVal itemCode As String, ByVal amount As Single, ByVal refDate As Date) As Double
        Try
            Dim vObj As SAPbobsCOM.SBObob
            Dim rs As SAPbobsCOM.Recordset
            vObj = PublicVariable.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoBridge)
            rs = PublicVariable.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset)
            rs = vObj.GetItemPrice(cardCode, itemCode, amount, refDate)
            If rs.RecordCount > 0 Then
                Return rs.Fields.Item(0).Value
            Else
                Return 0
            End If
        Catch ex As Exception
            Return 0
        End Try
    End Function

    Private Function ItemInfor(ByVal cardCode As String, ByVal itemCode As String, ByVal amount As Single, ByVal refDate As Date) As DataTable
        Dim dt As DataTable = Functions.SAP_Local_RunQuery("Select T0.ItemCode,T0.ItemName,T1.Rate from OITM T0 with(nolock) join OVTG T1 with(nolock) on T0.vatgourpsa=T1.Code  where itemcode='" + itemCode + "'")
        If dt.Rows.Count > 0 Then
            dt.Columns.Add("Price")
            dt.Rows(0).Item("Price") = GetSAPItemPrice(cardCode, itemCode, amount, refDate)
        End If

        Return dt
    End Function

    Private Sub LoadBackGroundPicture()
        Dim dvCopyFood As DataView = dvFood.ToTable.Copy.AsDataView
        dvCopyFood.RowFilter = Nothing
        dvCopyFood.RowFilter = "PicFileName <>''"
        'dvCopyFood.Item
    End Sub
    Private Sub AddItem2Bill()
        Dim strName As String = FoodGridEx.GetValue("Item_Name")
        Dim strItemCode As String = FoodGridEx.GetValue("Item_Code")
        Dim strUnitPrice As Double
        Dim dtItem As DataTable
        If strName Is DBNull.Value Then
            Return
        End If
        GridBill.BoundMode = BoundMode.Unbound
        GridBill.KeepRowSettings = True

        Dim tempRow As Janus.Windows.GridEX.GridEXRow
        tempRow = findRowGridBillById(strItemCode)
        If (tempRow Is Nothing) Then
            GridBill.BoundMode = BoundMode.Unbound
            GridBill.KeepRowSettings = True
            Dim newRow As GridEXRow = GridBill.AddItem()
            newRow.BeginEdit()
            newRow.Cells("ItemCode").Value = strItemCode
            newRow.Cells("ItemName").Value = strName
            newRow.Cells("Dscription").Value = strName
            newRow.Cells("Quantity").Value = 1
            dtItem = ItemInfor(GridCustomer.GetValue("CardCode").ToString, strItemCode, 1, Now.Date)

            strUnitPrice = dtItem.Rows(0).Item("Price")
            newRow.Cells("Price").Value = strUnitPrice
            newRow.Cells("Total").Value = strUnitPrice

            newRow.Cells("VatGroup").Value = "S2"
            newRow.Cells("VatPrcnt").Value = dtItem.Rows(0).Item("Rate")
            newRow.EndEdit()
        Else
            tempRow.BeginEdit()
            Dim NewQty As Decimal = CDbl(tempRow.Cells("Quantity").Value) + 1
            tempRow.Cells("Quantity").Value = NewQty
            dtItem = ItemInfor(GridCustomer.GetValue("CardCode").ToString, strItemCode, NewQty, Now.Date)

            strUnitPrice = dtItem.Rows(0).Item("Price")
            tempRow.Cells("Price").Value = strUnitPrice
            tempRow.Cells("Total").Value = strUnitPrice * NewQty
            tempRow.EndEdit()
        End If

        UpdateBill()
        FoodGridEx.SelectedItems.Clear()
    End Sub
#End Region

#Region "POST DOCUMENT TO SAP"

#Region "Insert into Table"
    Private Function InsertIntoORDR(ByVal dt As DataTable) As DataTable
        Dim drNew As DataRow = dt.NewRow
        drNew("DocDate") = CDate(Now.Date).ToString("yyyyMMdd")
        drNew("DocDueDate") = CDate(Now.Date).ToString("yyyyMMdd")
        drNew("CardCode") = GridCustomer.GetValue("CardCode").ToString
        drNew("CardName") = GridCustomer.GetValue("CardName").ToString
        drNew("DocTotal") = CDbl(lblBalanceDue.Text)
        drNew("U_TableCode") = TableCode
        dt.Rows.Add(drNew)
        Return dt
    End Function
    Private Function InsertIntoRDR1(ByVal dt As DataTable, ByVal dr As GridEXRow) As DataTable
        If dr.Cells.Item("Quantity").Value <> 0 Then
            Dim drNew As DataRow = dt.NewRow
            drNew("ItemCode") = dr.Cells.Item("ItemCode").Value
            drNew("Dscription") = dr.Cells.Item("Dscription").Value
            drNew("Quantity") = dr.Cells.Item("Quantity").Value
            drNew("DiscPrcnt") = dr.Cells.Item("DiscPrcnt").Value
            drNew("Price") = dr.Cells.Item("Price").Value
            dt.Rows.Add(drNew)
        End If
        Return dt
    End Function
    Private Function InsertIntoORCT(ByVal dt As DataTable) As DataTable
        Dim drNew As DataRow = dt.NewRow
        drNew("DocDate") = CDate(Now.Date).ToString("yyyyMMdd")
        drNew("DocDueDate") = CDate(Now.Date).ToString("yyyyMMdd")
        drNew("CardCode") = GridCustomer.GetValue("CardCode").ToString
        drNew("CashAcct") = CashAct
        drNew("CashSum") = CDbl(lblBalanceDue.Text)
        drNew("DocType") = "C"
        dt.Rows.Add(drNew)
        Return dt
    End Function
    Private Function InsertIntoRCT2(ByVal dt As DataTable, ByVal DocEntry_Invoice As String) As DataTable
        Dim drNew As DataRow = dt.NewRow
        Dim fn As New Functions
        drNew("DocEntry") = DocEntry_Invoice
        drNew("InvType") = "13"
        drNew("DocLine") = 0
        dt.Rows.Add(drNew)

        Return dt
    End Function
#End Region
    Public Function POST2SAP(ByVal ObjType As String, ByVal PaymentType As String) As String
        Try
            Dim xmlstr As String = ""
            Dim ds As New DataSet
            Dim ret As String = ""



            If Not PublicVariable.oCompany.Connected Then
                ret = oXML.ConnectSAP()
            End If

            If ret <> "" Then
                Return ret

            End If
            If PublicVariable.oCompany.InTransaction Then
                PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
            End If

            Dim dtHeader As DataTable = Functions.BuildTable("ORDR", "SlpCode;DocDate;CardCode;CardName;DocDueDate;ObjType;DocType;NumAtCard;Comments;DocTotal;U_TableCode")
            Dim dtLine As DataTable = Functions.BuildTable("RDR1", "ItemCode;Dscription;WhsCode;Quantity;LineNum;Price;PriceBefDi;DiscPrcnt")

            dtHeader = InsertIntoORDR(dtHeader)


            For Each dr As GridEXRow In GridBill.GetRows
                dtLine = InsertIntoRDR1(dtLine, dr)
            Next
            Select Case ObjType
                Case "13"
                    dtHeader.TableName = "OINV"
                    dtLine.TableName = "INV1"
                Case "17"
                    dtHeader.TableName = "ORDR"
                    dtLine.TableName = "RDR1"
                Case "15"
                    dtHeader.TableName = "ODLN"
                    dtLine.TableName = "DLN1"
            End Select

            ds.Tables.Add(dtHeader.Copy)
            ds.Tables.Add(dtLine.Copy)
            xmlstr = oXML.ToXMLStringFromDS(ObjType, ds)

            '----------------START TRANSACTION------------------------
            PublicVariable.oCompany.StartTransaction()

            ret = oXML.CreateMarketingDocument(xmlstr, ObjType)
            Dim DocEntry_Invoice As Integer
            If ret = "" Then
                DocEntry_Invoice = PublicVariable.oCompany.GetNewObjectKey()
            End If

            ret = ret.Replace("'", "")
            xmlstr = xmlstr.Replace("'", "")
            If ret <> "" Then
                If PublicVariable.oCompany.InTransaction Then
                    PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
                End If
            Else
                If ObjType = "13" And PaymentType <> "" Then
                    Dim dtORCT As DataTable = Functions.BuildTable("ORCT", "DocDate;DocDueDate;CardCode,CashAcct;CashSum;DocType")
                    Dim dtRCT2 As DataTable = Functions.BuildTable("RCT2", "DocEntry'InvType;SumApplied;DocLine")
                    dtORCT = InsertIntoORCT(dtORCT)
                    If dtORCT.Rows.Count > 0 Then
                        dtRCT2 = InsertIntoRCT2(dtRCT2, DocEntry_Invoice)

                        Dim paymentobjttype As String = ""
                        Dim DocTotal As Double = 0
                        DocTotal = CDbl(lblBalanceDue.Text)
                        If DocTotal <> 0 Then
                            If DocTotal < 0 Then
                                paymentobjttype = "46"
                                dtORCT.TableName = "OVPM"
                                dtRCT2.TableName = "VPM2"
                            Else
                                paymentobjttype = "24"
                                dtORCT.TableName = "ORCT"
                                dtRCT2.TableName = "RCT2"
                            End If



                            ds = New DataSet
                            ds.Tables.Add(dtORCT.Copy)
                            ds.Tables.Add(dtRCT2.Copy)
                            xmlstr = oXML.ToXMLStringFromDS(paymentobjttype, ds)

                            ret = oXML.CreateMarketingDocument(xmlstr, paymentobjttype)


                            ret = ret.Replace("'", "")
                            xmlstr = xmlstr.Replace("'", "")
                            If ret <> "" Then
                                If PublicVariable.oCompany.InTransaction Then
                                    PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
                                End If
                            Else
                                If PublicVariable.oCompany.InTransaction Then
                                    PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
                                End If
                            End If
                        Else
                            If PublicVariable.oCompany.InTransaction Then
                                PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
                            End If
                        End If
                    Else
                        If PublicVariable.oCompany.InTransaction Then
                            PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
                        End If
                    End If
                Else
                    If PublicVariable.oCompany.InTransaction Then
                        PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
                    End If
                End If
            End If
            Return ret
        Catch ex As Exception
            If PublicVariable.oCompany.InTransaction Then
                PublicVariable.oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
            End If
            Return ex.ToString
        End Try
    End Function
#End Region

    Private Sub LoadDocument(ByVal DocEntry As String, ByVal ObjType As String)
        

        Dim dt As DataTable = Functions.SAP_Local_RunQuery("select T0.ItemCode,T0.Dscription, T0.Quantity ,T0.Price, T0.GTotal,T0.vatgroup, T0.VatPrcnt, T1.CardCode  from RDR1 T0 with(nolock) join ORDR T1 with(nolock) on T0.DocEntry=T1.DocEntry where T0.DocEntry=" + DocEntry)
        GridBill.BoundMode = BoundMode.Unbound
        GridBill.KeepRowSettings = True

        Dim dtCustomer As DataTable = Functions.SAP_Local_RunQuery("Select CardCode,CardName,Address from OCRD where CardCode='" + dt.Rows(0).Item("CardCode").ToString + "'")
        GridCustomer.DataSource = dtCustomer

        For Each dr As DataRow In dt.Rows
            
            Dim newRow As GridEXRow = GridBill.AddItem()
            newRow.BeginEdit()
            newRow.Cells("ItemCode").Value = dr("ItemCode").ToString
            newRow.Cells("ItemName").Value = dr("Dscription").ToString
            newRow.Cells("Dscription").Value = dr("Dscription").ToString
            newRow.Cells("Quantity").Value = dr("Quantity")
            newRow.Cells("Price").Value = dr("Price")
            newRow.Cells("Total").Value = dr("GTotal")
            newRow.Cells("VatGroup").Value = dr("vatgroup")
            newRow.Cells("VatPrcnt").Value = dr("VatPrcnt")
            newRow.EndEdit()
        Next
    End Sub

End Class